package com.purchase.interceptor;

import com.alibaba.fastjson.JSON;
import com.purchase.util.AuthUtil;
import com.purchase.util.LogInfo;
import com.purchase.util.ResponseForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        ResponseForm result = new ResponseForm();
        //用户认证
        try {
            AuthUtil.getUserId(request);
            return true;
        } catch (Exception e) {
            log.error(LogInfo.AUTH_ERROR, e);
            result.setStatus(false);
            result.setCode("500");
            result.setMessage(LogInfo.AUTH_ERROR);
            response.setContentType("application/json; charset=UTF-8");
            String jsonString = JSON.toJSONString(result);
            response.getWriter().print(jsonString);
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
